package net.ib.mtalk.util;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import net.ib.mntalk.protocol.Common;
import android.util.Log;

public class TimeAdapter {
	public final static long TIME_MILLISECOND 		= 1L;
	public final static long TIME_SECOND 			= TIME_MILLISECOND * 1000;
	public final static long TIME_MINUTE 			= TIME_SECOND * 60;
	public final static long TIME_HOUR 				= TIME_MINUTE * 60;
	public final static long TIME_DAY 				= TIME_HOUR * 24;
	public final static long TIME_WEEK 				= TIME_DAY * 7;
	public final static long TIME_YEAR 				= TIME_DAY * 365;
	
	public final static int DATE_CHANGED_NONE		= 0;
	public final static int DATE_CHANGED_DAY_ONE 	= 1;
	public final static int DATE_CHANGED_DAY_TWO 	= 2;
	public final static int DATE_CHANGED_DAY_THREE 	= 3;
	public final static int DATE_CHANGED_DAY_FOUR 	= 4;
	public final static int DATE_CHANGED_DAY_FIVE 	= 5;
	public final static int DATE_CHANGED_DAY_SIX 	= 6;
	public final static int DATE_CHANGED_WEEK 		= 11;
	public final static int DATE_CHANGED_MONTH 		= 12;
	public final static int DATE_CHANGED_YEAR 		= 13;
	
	public static enum WEEK_DAY {
		MONDAY,
		TUESDAY,
		WEDNESDAY,
		THURSDAY,
		FRIDAY,
		SATURDAY,
		SUNDAY
	}
	/**
	 * 비교할 DATE 와 현재 시간 DATE 를 넘겨주면 변경된 날짜 정보를 알려준다.
	 * @param compareDate 비교할 날짜의 DATE
	 * @param currentDate 현재 시간 DATE
	 * @return
	 */
	public static int CompareDate(Date compareDate, Date currentDate){
		/**
		 * 비교할 데이터 생각해보기!
		 *  - 날짜(년). 년단위 판단
		 *  - 날짜(월). 월단위 판단
		 *  - 날짜(일). 일단위 판단
		 *  - 요일. 요일판단
		 */
		
		if(currentDate == null){
			currentDate = new Date(System.currentTimeMillis());
		}
		
		// 1. 바뀐 날짜가 있는지 확인하자!
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMwwdd");
		if((Integer.parseInt(sdf.format(compareDate))) == Integer.parseInt(sdf.format(currentDate))){
			return DATE_CHANGED_NONE;
		}else{
			sdf = new SimpleDateFormat("dd");
			
			// 2. 있다! 그러면 년도가 바뀌었는가?
			sdf = new SimpleDateFormat("yy");
			if(Integer.parseInt(sdf.format(compareDate)) != Integer.parseInt(sdf.format(currentDate))){
				// 헉 년도가 바뀌었다!! 두둥!! 가버려
				return DATE_CHANGED_YEAR;
			}
			
			// 3. 년도는 바뀌지 않았다! 월이 바뀌었는가? 
			sdf = new SimpleDateFormat("MM");
			if(Integer.parseInt(sdf.format(compareDate)) != Integer.parseInt(sdf.format(currentDate))){
				// 달이 또 지나가 버렸구만... 시간참 빠르다.
				return DATE_CHANGED_MONTH;
			}
			
			// 4. 주가 바뀌었는가? 년/월은 바뀌지 않았다.
			sdf = new SimpleDateFormat("ww");
			if(Integer.parseInt(sdf.format(compareDate)) != Integer.parseInt(sdf.format(currentDate))){
				// 지난주엔 뭐했지?
				return DATE_CHANGED_WEEK;
			}
			
			// 5. 년/월/주 가 바뀌지 않았다. 바뀐 날짜로 리턴하자!
			sdf = new SimpleDateFormat("dd");
			return (Integer.parseInt(sdf.format(currentDate)) - Integer.parseInt(sdf.format(compareDate)));
		}
	}
	
    /**
     * 두 시간을 비교해서 변경된 시간을 알려준다..
     * @param compareTime
     * @param currentTime
     * @return
     */
    public static int CompareTimeLong(long compareTime, long currentTime){
    	try{    		
    		return CompareDate((new Date(compareTime)), (new Date(currentTime)));
    	}catch(NumberFormatException e){
    		MTalkLogWriter.e(e);
    		return 0;
    	}
    }
	
	/**
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
    public static String Date2Str(Date date, String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}
    
    public static String LongDate2Str(long longTime, String format){
    	return Date2Str(new Date(longTime), format);
    }
    
    /**
     * UUID로 millisecond값을 리턴한다
     * @param uuid
     * @return
     */
    public static long getMillisecondFromUUID(java.util.UUID uuid){
    	try{
    		long timestamp = uuid.timestamp();
    		return (timestamp / 10000) -12219292800000L;    
    	}catch(Exception e){
    		MTalkLogWriter.e(e);
    	}
    	return System.currentTimeMillis();
    }
    
    public static long getMillisecondFromUUIDMsg(Common.UUIDMsg uuidMsg){
    	return getMillisecondFromUUID(GpbSupport.makeUuid(uuidMsg));
    }
    
    public static String getCurruntTimeStr(){
		Calendar rightNow = Calendar.getInstance();// 날짜 불러오는 함수

		String timestr 
		 	 = new String ( rightNow.get(Calendar.YEAR) 
		 			+ String.format("%02d",rightNow.get(Calendar.MONTH)) 
		 			+ String.format("%02d",rightNow.get(Calendar.DATE))
		 			+ String.format("%02d",rightNow.get(Calendar.HOUR)) 
		 			+ String.format("%02d",rightNow.get(Calendar.MINUTE))
		 			+ String.format("%02d",rightNow.get(Calendar.SECOND)) );
		return timestr;
	}
    
    /**
     *
     * @param dateStr
     * @return
     */
    public static Date UTC2Date(String dateStr) {
        String timePattern = "";

        // select the time pattern to use:
        if (dateStr.length() == 6) {
            timePattern = "yyMMdd";
        }
        if (dateStr.length() == 8) {
            timePattern = "yyyyMMdd";
        } else if (dateStr.length() == 12) {
            timePattern = "yyyyMMddHHmm";
        } else if (dateStr.length() == 13) {
            timePattern = "yyyyMMdd'T'HHmm";
        } else if (dateStr.length() == 14) {
            timePattern = "yyyyMMddHHmmss";
        } else if (dateStr.length() == 15) {
            timePattern = "yyyyMMdd'T'HHmmss";
        } else if (dateStr.length() == 16) {
        	timePattern = "yyyyMMdd'T'HHmmss";
        }else{
            timePattern = "yyyyMMdd'T'HHmmss'Z'";
        }
        // alternative UTC format with hyphens
        if (dateStr.indexOf('-') > -1) {
            timePattern = "yyyy-MM-dd'T'HH:mm:ssZ";
            if (dateStr.length() <= 10)
            timePattern = timePattern.substring(0,dateStr.length() - 1);
            else if (dateStr.length() > 11)
            timePattern = timePattern.substring(0,Math.min(timePattern.length()-1,dateStr.length() + 1));

        }
        
      //  System.out.println("timePattern="+timePattern);
        // Format the current time.
        SimpleDateFormat formatter = new SimpleDateFormat(timePattern);


   //     formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

        Date d = null;
        try {
            d = formatter.parse(dateStr, new ParsePosition(0));
        } catch (NullPointerException e) {
        	MTalkLogWriter.e(e);
        }

        return d;
    }
    
    public static String Date2UTC(Date date) {

        String timePattern = "yyyyMMdd'T'HHmmss";

        SimpleDateFormat formatter = new SimpleDateFormat(timePattern);

//        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

        String f = formatter.format(date);
        return f+"Z";
    }
}
